﻿using System;
using System.Linq;
using System.Reflection;

namespace WindowServices.Config
{
    class PlugHelper : MarshalByRefObject
    {
        public static bool CheckType(string type)
        {
            AppDomain domain = null;
            try
            {
                var appsetup = new AppDomainSetup();
                //appsetup.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;// string.Format("Plug\\{0}\\{1}", serviceEntity.ID, serviceEntity.Version);
                appsetup.PrivateBinPath = string.Format("{0}\\temp;", AppDomain.CurrentDomain.BaseDirectory.TrimEnd('/'));
                domain = AppDomain.CreateDomain("temp", null, appsetup);
                var oh = domain.CreateInstance(typeof(PlugHelper).Assembly.FullName, typeof(PlugHelper).FullName);
                var ph = (PlugHelper)oh.Unwrap();
                return ph.CheckType1(type);
            }
            catch
            {
                return false;
            }
            finally
            {
                if (domain != null)
                {
                    AppDomain.Unload(domain);
                }
            }
        }

        private bool CheckType1(string type)
        {
            object ob = Assembly.Load(type.Split(',')[1]).CreateInstance(type.Split(',')[0]);

            if (ob != null)
                return ob.GetType().GetInterfaces().Any(t => t == typeof (Interface.IService));

            return false;
        }
    }


    [Serializable]
    public class ServiceInfo
    {
        public Guid Id
        {
            get;
            set;
        }

        public string Name { get; set; }
        public string Type { get; set; }

        public Version Version { get; set; }

        public string Description { get; set; }
    }
}
